<template>
  <div class="container">
    <el-row class="searchInputWidth">
      <el-form :inline="true" :model="filterField" ref="listForm">
        <el-form-item label="地区选择" class="row-padding-bottom">
          <el-cascader
            ref="areas"
            v-model="filterFieldArea"
            :options="areasOptions"
            @change="getAreaIdSearch"
            clearable
            filterable
            placeholder="请选择"
            class="proInputWidth"
            :props="{ checkStrictly: false }"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="行业选择" class="row-padding-bottom">
          <el-select
            clearable
            filterable
            placeholder="请选择"
            class="proInputWidth"
            v-model="filterField.industryId"
          >
            <el-option
              v-for="item in industryOptions"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="icon iconfont iconchazhao1"
            @click="searchTable"
            class="commonBtn"
          />
        </el-form-item>
        <el-form-item class="fr">
          <el-button
            class="commonBut saveBtn funComBut"
            icon="iconfont icontianjia"
            @click="onAdd"
            v-show="isShowAdd"
          >
            <span class="opetareText">新增设置</span>
          </el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <!-- 列表 -->
    <el-table
      :data="tableList"
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      highlight-current-row
      stripe
      v-loading="loading"
      style="border: 1px solid #dfe6ec"
    >
      <el-table-column align="center" prop="cityName" label="市/州" />
      <el-table-column align="center" prop="countyName" label="区/县" />
      <el-table-column align="center" prop="industryName" label="行业" />
      <el-table-column
        align="center"
        prop="scale"
        label="工资专户拨付比例"
        :formatter="formatTd"
      />
      <el-table-column
        align="center"
        prop="calculateTypeDesc"
        label="总额计算方式"
        :formatter="formatTd"
      />
      <el-table-column
        align="center"
        prop="typeDesc"
        label="拨付方式"
        :formatter="formatTd"
      />
      <el-table-column align="left" label="操作" width="180px" fixed="right">
        <template slot-scope="scope">
          <el-link
            type="primary"
            @click="onUpdate(scope.$index, scope.row)"
            v-show="isShowUpdate"
            >修改</el-link
          >
          <el-link
            type="primary"
            @click="onDel(scope.row.id)"
            v-show="isShowDel"
            >删除</el-link
          >
          <span v-show="!isShowDel && !isShowUpdate">--</span>
        </template>
      </el-table-column>
      <!-- 表格数据为空时，页面显示 -->
      <div slot="empty" v-show="isEmpty">
        <emptyTable emptyText="暂无相关信息" />
      </div>
    </el-table>
    <!-- filterField为搜索条件 -->
    <Pagination
      ref="pagination"
      @getList="getTableList"
      :filterField="filterField"
      :requestUrl="requestUrl"
      @getpageSize="getpageSize"
      @getpageNo="getpageNo"
    />
    <div>
      <el-dialog
        :title="dialogTitle"
        v-if="dialogVisible"
        :visible.sync="dialogVisible"
        width="40%"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        @close="closeDialog"
      >
        <el-form
          class="el-form1"
          :model="formData"
          ref="formRef"
          :rules="rules"
          label-width="160px"
        >
          <el-form-item label="区域：" prop="areaId">
            <el-cascader
              ref="areas"
              v-model="formArea"
              :options="areasOptions"
              @change="getAreaId"
              clearable
              filterable
              placeholder="请选择"
              class="form-item"
              :props="{ checkStrictly: true }"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="行业：" prop="industryArray">
            <el-select
              clearable
              filterable
              multiple
              placeholder="请选择"
              class="form-item"
              v-model="formData.industryArray"
            >
              <el-option
                v-for="item in industryOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="拨付总额计算方式：" prop="calcType">
            <el-select
              clearable
              filterable
              placeholder="请选择"
              class="form-item"
              v-model="formData.calcType"
            >
              <el-option
                v-for="item in calcTypeList"
                :key="item.type"
                :label="item.name"
                :value="item.type"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="formData.calcType === 'SCALE'"
            label="工资专户拨付比例："
            prop="scale"
          >
            <el-input
              placeholder="请输入工资专户拨付比例"
              v-model.trim="formData.scale"
              class="form-item"
            ></el-input
            >&ensp;%
          </el-form-item>
          <!-- <el-form-item label="拨付方式" prop="type">
            <el-select
              clearable
              filterable
              placeholder="请选择"
              class="form-item"
              v-model="formData.type"
            >
              <el-option
                v-for="item in bursetype"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>-->
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeDialog" class="cancel">取 消</el-button>
          <el-button
            type="primary"
            @click="onSave"
            :loading="isSaveLoading"
            v-show="isShowSave"
            class="save"
            >保 存</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'

export default {
  name: 'allocationSetList',
  components: {},
  props: {
    basicConfig: {
      type: String,
      default: '',
    },
  },
  data() {
    const validateAcquaintance = (rule, value, callback) => {
      if (value < 0 || value > 100) {
        callback(new Error('请输入1-100的数字'))
      } else {
        callback()
      }
    }
    return {
      // 搜索条件
      requestUrl: 'api-acc/cs/accassconfig/expand/findbypage',
      filterField: {
        areaId: '',
        industryId: '',
      },
      pageSize: 20,
      pageNo: 1,
      // 表格数据
      tableList: [],
      loading: false,
      isEmpty: false,
      // 弹窗
      dialogVisible: false,
      dialogTitle: '',
      formData: {
        id: '',
        areaId: '',
        industryArray: [],
        scale: '',
        type: 'MONTHLY',
        calcType: '', //拨付总额计算方式
      },
      rules: {
        areaId: [{ required: true, message: '请选择区域', trigger: 'change' }],
        industryArray: [
          {
            type: 'array',
            required: true,
            message: '请选择行业',
            trigger: 'change',
          },
        ],
        calcType: [
          {
            required: true,
            message: '请选择拨付总额计算方式',
            trigger: 'change',
          },
        ],
        scale: [
          {
            required: true,
            message: '工资专户拨付比例不能为空',
            trigger: 'blur',
          },
          {
            type: 'number',
            message: '工资专户拨付比例为数字值',
            trigger: 'blur',
            transform: (value) => Number(value),
          },
          { validator: validateAcquaintance, trigger: 'blur' },
        ],
      },
      filterFieldArea: [],
      formArea: [],
      bursetype: [], //拨付设置
      calcTypeList: [
        { type: 'SCALE', name: '按照比例' },
        { type: 'CONTRACT', name: '按照合同' },
      ], //拨付总额计算方式
      isSaveLoading: false, //保存按钮加载
      // 页面按钮权限
      isShowDel: '',
      isShowUpdate: '',
      isShowAdd: '',
      isShowSave: '',
    }
  },
  computed: {
    ...mapState(['areasOptions', 'industryOptions']),
  },
  created() {
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
    this.getAreas({ areaId: this.$store.state.areaInfoArr.areaId })
    this.getIndustry({})
    if (this.basicConfig === 'AUTO') {
      // this.formData.calcType = "SCALE";
      this.calcTypeList = [{ type: 'SCALE', name: '按照比例' }]
    }
    this.isShowAdd =
      this.$store.state.buttonLimitsArr.indexOf('allocationSet:add') > -1
    this.isShowUpdate =
      this.$store.state.buttonLimitsArr.indexOf('allocationSet:update') > -1
    this.isShowDel =
      this.$store.state.buttonLimitsArr.indexOf('allocationSet:delete') > -1
    this.isShowSave =
      this.$store.state.buttonLimitsArr.indexOf('allocationSet:add') > -1 ||
      this.$store.state.buttonLimitsArr.indexOf('allocationSet:update') > -1
  },
  methods: {
    getpageSize(val) {
      this.pageSize = val
    },
    getpageNo(val) {
      this.pageNo = val
    },
    ...mapActions([
      // 'areasOptions',
      // 'industryOptions',
      'getAreas',
      'getIndustry',
    ]),
    getTableList(data) {
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isEmpty = true
      }
    },
    searchTable() {
      this.loading = true
      this.$refs.pagination.getTableListData()
    },
    closeDialog() {
      // this.formData.resetFields();
      this.formData.id = ''
      this.formData.areaId = ''
      this.formData.industryArray = []
      this.formData.scale = ''
      // this.formData.type = "";
      this.formData.calcType = ''
      this.formArea = []
      this.dialogVisible = false
    },
    // 新增设置
    onAdd() {
      this.dialogTitle = '设置专户拨付计划条件'
      this.dialogVisible = true

      // console.log(222, this.formData);
    },
    // 修改设置
    onUpdate(index, item) {
      this.dialogTitle = '修改专户拨付计划条件'
      this.getAllocatedById(item.id)
    },
    getAllocatedById(id) {
      this.axios({
        method: 'post',
        url: 'api-acc/cs/accassconfig/expand/findbyid',
        data: {
          id: id,
        },
      })
        .then((res) => {
          this.formData.id = res.data.result.id
          this.formData.areaId = res.data.result.areaId
          this.formData.industryArray = []
          this.formData.industryArray.push(res.data.result.industryId)
          this.formData.scale = res.data.result.scale
          this.formData.calcType = res.data.result.calculateType
          this.formArea = res.data.result.areaId
          this.dialogVisible = true
        })
        .catch((error) => {
          this.$message({
            showClose: true,
            duration: 3000,
            message: '获取专户拨付计划数据失败',
            type: 'error',
          })
        })
    },
    // 删除设置
    onDel(id) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.delAllocatedSet(id)
        })
        .catch(() => {})
    },
    delAllocatedSet(id) {
      this.axios({
        method: 'post',
        url: 'api-acc/cs/accassconfig/expand/remove',
        data: {
          id: id,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.$message({
                message: '删除成功',
                type: 'success',
              })
              this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    // 保存设置
    onSave() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 保存更新
          this.isSaveLoading = true
          this.submitForm()
        } else {
          return false
        }
      })
    },
    submitForm() {
      var data = {
        id: this.formData.id,
        areaId: this.formData.areaId,
        industryArray: this.formData.industryArray.toString(),
        calculateType: this.formData.calcType,
        type: 'MONTHLY',
      }
      if (this.formData.calcType === 'SCALE') {
        data.scale = this.formData.scale
      }
      this.axios({
        method: 'post',
        url: 'api-acc/cs/accassconfig/expand/addoredit',
        data: data,
      })
        .then((response) => {
          this.isSaveLoading = false
          if (!response.data.hasError) {
            // this.dialogVisible = false;
            this.closeDialog()
            this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
            this.$message({
              message: '设置专户拨付计划条件成功',
              type: 'success',
            })
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
            this.isSaveLoading = false
          }
        })
        .catch((error) => {
          this.$message.error('设置专户拨付计划条件失败')
          this.isSaveLoading = false
        })
    },
    //获取搜索选中的区域最后一级id
    getAreaIdSearch() {
      // console.log(this.filterFieldArea);
      this.filterField.areaId =
        this.filterFieldArea[this.filterFieldArea.length - 1]
    },
    //获取dialog选中的区域最后一级id
    getAreaId() {
      // console.log(this.formArea);
      this.formData.areaId = this.formArea[this.formArea.length - 1]
    },
  },
}
</script>

<style lang="less" scoped>
.container {
  .el-form1 {
    margin-top: 20px; //修改搜索栏上下间距为24px
  }
}
@media screen and (min-width: 1280px) and (max-width: 1366px) {
  .searchInputWidth /deep/.el-form-item__label {
    width: 82px;
  }
}
.form-item {
  width: 300px;
}
</style>
